package applicationFunction.socks.nwct;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.FileHandler;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;

/**
 * 放在公网机的启动类
 */
public class GMain {
    private static Logger logger = Logger.getLogger("applicationFunction.socks.nwct.GMain");
    public static void main(String[] args) {
        init();
        GMain nwct = new GMain();
        nwct.startNwct();
    }



    public static void init(){

        try {
            Logger logger = Logger.getLogger("applicationFunction.socks.nwct");//  logger对象的名称
            FileHandler fh = new FileHandler("gmain.log");
            SimpleFormatter sf = new SimpleFormatter();
            fh.setFormatter(sf);
            logger.addHandler(fh);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void  startNwct(){
        SocketPoolServer socketPool = null;//
        ServerSocket serverSocket = null;
        try {
            socketPool = new SocketPoolServer();
            socketPool.start(6666);//用于给内网机使用的端口号
            serverSocket = new ServerSocket(7777);//给客户机使用的端口号
            Socket orgin = null;
            while (true) {
                orgin = serverSocket.accept();
                Socket proxy = socketPool.useSocket();
                handle(orgin,proxy);
            }

        }
        catch (IOException e) {
            logger.severe("start error ");
            e.printStackTrace();
        }

    }

    public void handle(Socket orgin,Socket dest){
        try {
            if(orgin!=null){
                logger.info("handler orgin "+orgin.getInetAddress());
            }
            if(dest == null){
                logger.severe("proxy is lack");
                return;
            }
            logger.info("handler dest " + dest.getInetAddress());
            Tunnel t1 = new Tunnel(orgin.getInputStream(), dest.getOutputStream());
            Tunnel t2 = new Tunnel(dest.getInputStream(), orgin.getOutputStream());
            t1.start();
            t2.start();
        }
        catch (IOException e) {
            e.printStackTrace();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
